#!/bin/sh
#
# parallel export sql file
#
# 2022-11-02: Created by yike
#

# vi tasklist
# old_table -> new_table -> sql_file
# GSP_PURCHASE_ORDER -> od_purchase_order -> od_purchase_order
# GSP_PURCHASE_ORDER_ITEM -> od_purchase_order_item -> od_purchase_order_item

function para_init() {
    tempfifo="my_temp_fifo"
    mkfifo ${tempfifo}
    exec 6<>${tempfifo}
    rm -f ${tempfifo}
    for ((i = 1; i <= ${thread_num}; i++)); do
        echo
    done >&6
}

function para_run() {
    OLD_IFS=$IFS
    IFS=$'\n'
    i=0
    for task in $1; do
        i=$((i + 1))
        read -u6
        {
            para_stask "$task" "$i"
            echo "" >&6
        } &
    done
    IFS=$OLD_IFS
    wait
    exec 6>&-
}

# 等待空间, 可用空间小于 50G, 等待释放空间
function wait_space() {
    while true; do
        free_space=$(df -h /oracle | grep oracle | awk '{print $4}' | sed 's/G//')
        if [ $free_space -lt 50 ]; then
            printf "%s: [%02d] Waiting for free space\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$1"
        else
            break
        fi
        sleep 5
    done
}

# 上传文件
function upload() {
    printf "%s: [%02d] uploading %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$2" "$1"
    curl -T ${1}.sql ftp://10.0.190.81:7820/ >/dev/null 2>&1
    curl -T exp_${1}.log ftp://10.0.190.81:7820/ >/dev/null 2>&1
    rm -f ${1}.sql
}

# 任务函数
function para_stask() {
    old_table=$(echo $1 | awk -F' -> ' '{print $1}')
    new_table=$(echo $1 | awk -F' -> ' '{print $2}')
    new_file=$(echo $1 | awk -F' -> ' '{print $3}')

    printf "%s: [%02d] Doing %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$2" "$1"
    wait_space "$2"
    ./oracle_mysql_v0_1_4 --ob BPM --oh 10.0.15.215 --ok 'p18SUC8AaIQJI6W2kkbZIA==' --sql ${old_table}.txt --tt ${new_table} --file ${new_file}.sql --pre-sql 'alter session set current_schema = GSPMODULE' >exp_${new_file}.log 2>&1
    upload $new_file $2
    printf "%s: [%02d] Done  %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$2" "$1"
}

function main() {
    tasklist=$(cat tasklist | grep -v '^#') # 任务列表
    thread_num=4                            # 并发数

    para_init "$thread_num"
    para_run "$tasklist"
}

echo "$(date '+%Y-%m-%d %H:%M:%S'): Begin"
main
echo "$(date '+%Y-%m-%d %H:%M:%S'): Done"
